package com.josework.springhelloworld.utils.forkjoin;

import java.util.Spliterator;
import java.util.function.Function;
import java.util.stream.LongStream;

public class Accumulator {

    public long total = 0;
    public void add(long value){
        total += value;
    }

    public static long measurePerf(Function<Long,Long> function, long n){
        return function.apply(n);
    }

    public static long sideEffectSum(long n){
        Accumulator accumulator = new Accumulator();
        LongStream.rangeClosed(1,n)
                .forEach(accumulator::add);
        return accumulator.total;
    }

    public static long sideEffectParallelSum(long n){
        Accumulator accumulator = new Accumulator();
        LongStream.rangeClosed(1,n)
                .parallel()
                .forEach(accumulator::add);
        return accumulator.total;
    }

    public static void main(String[] args) {
        System.out.println("SideEffect parallel sum done in: " +
                        measurePerf(Accumulator::sideEffectParallelSum, 10_000_000) +"" +
                "msecs" );

        System.out.println("ForkJoin sum done in: " + measurePerf(
                ForkJoinSumCalculator::forkJoinSum, 10_000_000) + " msecs" );

    }


}
